package com.yi.wood.web.util;

import com.alibaba.fastjson.JSON;
import com.yi.wood.service.po.UserCachePo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Created by moyi on 2019/4/4 16:15
 *
 * @author moyi
 */
@Component
public class UserCacheUtil {

    @Resource
    private RedisTemplate redisTemplate;

    private static final String TOKEN_PREFIX = "com:yi:token:";
    /**
     * token 过期时间，默认单位小时
     */
    private static final Long EXPIRE_TIME = 12L;

    /**
     * 从缓存中获取对应token的用户信息
     * @param key 缓存KEY
     * @return 缓存的用户相关信息
     */
    public UserCachePo getUserByCache(String key){
        Object obj = redisTemplate.boundValueOps(TOKEN_PREFIX+key).get();
        if (obj != null){
            String json = obj.toString();
            return JSON.parseObject(json, UserCachePo.class);
        }
        return null;
    }

    /**
     * 存入一个用户信息到缓存中,有一定过期时间
     * @param key 缓存KEY
     * @param obj 对象
     */
    public void cacheUser(String key, Object obj){
        redisTemplate.boundValueOps(TOKEN_PREFIX+key).set(JSON.toJSONString(obj), EXPIRE_TIME, TimeUnit.HOURS);
    }
}
